package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.security.MessageDigest

/**
 *
 * @Title: apiTpTdxGetInvolved*
 * @Description:泰迪熊人工介入
 * @remak ：提供给浙江泰迪熊系统人工介入通知
 * @author: TH*
 * @date 2023-10-16 11:11:00
 *
 */
public  class apiTpTdxGetInvolved implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiTpTdxGetInvolved.class);


    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //初始化返回参数
        JSONObject result =new JSONObject();

        long starttime=System.currentTimeMillis();

        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        //获取接口调用方式及参数
        String GetMethod=httpServletRequest.getMethod();
        log.debug("[GetMethod]:"+GetMethod);

        String inData="";
        if (GetMethod.equals("GET")){
            inData=httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]"+inData);
        }else {
            InputStreamReader reader=new InputStreamReader(httpServletRequest.getInputStream(),"UTF-8");
            BufferedReader iny=new BufferedReader(reader);
            String line;
            while ((line=iny.readLine())!=null){
                inData+=line;
            }
            log.debug("[原始Post请求参数：]"+inData);
        }
        log.debug("[调用请求信息：]"+inData)


        if (KHUtil.isNull(inData)){
            log.error("入参为空-无法完成操作！");
            result.put("code",-2);
            result.put("message","入参为空-无法完成操作！");

            return  result.toString();
        }



        try {

            JSONObject inJson = JSONObject.fromObject(inData);
            String taskId = GetJV(inJson, "taskId");//任务ID
            String timestamp = GetJV(inJson, "timestamp");//时间戳
            String customerName = GetJV(inJson, "customerName");//客户姓名
            String customerPhone = GetJV(inJson, "customerPhone");//手机号
            String objective_Guid=null;
            String token = GetJV(inJson, "token");//token
            String exendFieds=GetJV(inJson,"extendFields");
            if (!KHUtil.isNull(exendFieds)) {
                JSONObject  exendFiedsJson=JSONObject.fromObject(exendFieds);
               objective_Guid=GetJV(exendFiedsJson,"EXTEND1");//任务名单ID


            }



            String IsNullMSG =
                            KHUtil.isNullMSG("taskId", taskId) +
                            KHUtil.isNullMSG("timestamp", timestamp) +
                            KHUtil.isNullMSG("token", token)+
                                    KHUtil.isNullMSG("extendFields",exendFieds)+
                                    KHUtil.isNullMSG("EXTEND1",objective_Guid)+
                                    KHUtil.isNullMSG("customerName", customerName)+
                            KHUtil.isNullMSG("customerPhone", customerPhone)
            ;
            if (!KHUtil.isNull(IsNullMSG)) {
                log.error("参数为必填项-无法完成操作！");
                result.put("code", -2);
                result.put("message", IsNullMSG + "参数为空-无法完成操作！");
                return result.toString();
            }


            /**
             * MD5(accessKey+timestamp+orgName)
             * accessKey是双方协商的参数
             */
            String accessKey = KHDBConfig.getParam(eliteBean, "TDKEY", "");//获取accessKey
            String orgName = KHDBConfig.getParam(eliteBean, "TDXQID", "");//orgName	企业id
            String isString = MD5(accessKey.toString() + timestamp.toString() + orgName.toString());//加个密看看
            log.debug("预期加密Token:" + isString);
            //校验通过
            if (token.equals(isString)) {
                log.debug("Token校验通过！");


            } else {
                log.error("Token校验不通过！");
                result.put("code", -2);
                result.put("message", "Token校验不通过-无法完成操作！");
                return result.toString();
            }
            //消息内容拼接
            String msg_input="【浙江泰迪熊系统】：您有一条需要人工介入的任务"+"\n任务ID:"+taskId.toString()+"\n客户姓名:"+customerName+"\n客户手机号："+customerPhone;

             String insertSql='''   
                            Insert 
                            Into
                                TDX_GETINVOLVED_LIST
                                (
                                rec_guid,
                                OBJECTIVE_GUID,
                                TASKID,
                                CUSTOMERNAME,
                                MOBILE,
                                MSG_COUNT,
                                MSG_LOADCOUNT,
                                MSG_TYPE,
                                CREATEDDATE,
                                MSG_INPUT
                                )VALUES(
                                sysguid,
                                ?,
                                ?,
                                ?,
                                ?,
                                1,
                                0,
                                '泰迪熊人工介入通知',
                                sysdate,
                                ?
                                )
                              ''';

            jt.update(insertSql,objective_Guid,taskId,customerName,customerPhone,msg_input);








            long endtime=System.currentTimeMillis();
            result.put("code", 200);
            result.put("message","处理成功！耗时:"+(endtime-starttime)+"毫秒");
            result.put("timestamp",timestamp);




        }catch (Exception e) {
            log.error("接口处理异常", e);
            result.put("code", -1);
            result.put("message","接口处理异常:"+ e.getMessage());

        }

        return result.toString();
    }



    // MD5加码。32位
    public static String MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];

        byte[] md5Bytes = md5.digest(byteArray);

        StringBuffer hexValue = new StringBuffer();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }


    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }
}
